package com.neu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.neu.common.utils.HttpUtils;
import com.neu.gulimall.member.dao.MemberLevelDao;
import com.neu.gulimall.member.entity.MemberLevelEntity;
import com.neu.gulimall.member.exception.GetGiteeInfoException;
import com.neu.gulimall.member.exception.PhoneExistException;
import com.neu.gulimall.member.exception.UsernameExistException;
import com.neu.gulimall.member.vo.MemberLoginVo;
import com.neu.gulimall.member.vo.MemberRegisterVo;
import com.neu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.common.utils.PageUtils;
import com.neu.common.utils.Query;

import com.neu.gulimall.member.dao.MemberDao;
import com.neu.gulimall.member.entity.MemberEntity;
import com.neu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 创建新用户
     * @param vo
     */
    @Override
    public void regist(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        // 设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        // 检查用户名和手机号是否唯一   为了让controller能够感知异常，使用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setNickname(vo.getUsername());

        //密码要进行加密存储
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        // 其他的默认信息
        memberEntity.setCreateTime(new Date());

        // 保存
        baseMapper.insert(memberEntity);
    }

    /**
     * 检查手机号是否重复
     * @param phone
     * @throws PhoneExistException
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0){ // 手机号已存在
            throw new PhoneExistException();
        }
    }

    /**
     * 检查用户名是否重复
     * @param username
     * @throws UsernameExistException
     */
    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0){
            throw new UsernameExistException();
        }
    }

    /**
     * 用户账号密码登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String username = vo.getUsername(); // 用户登录账号，使用用户名或手机号登录
        String password = vo.getPassword();

        // 去数据库中查询 用户加密后的密码
        MemberEntity memberEntity = baseMapper.selectOne(
                new QueryWrapper<MemberEntity>().eq("username", username).or().eq("mobile", username));

        if (memberEntity == null){
            // 登录失败
            return null;
        }else {
            // 进一步判断用户名与密码是否匹配
            String passwordDb = memberEntity.getPassword();

            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (encoder.matches(password,passwordDb)){
                // 密码匹配
                return memberEntity;
            }else {
                // 密码不匹配
                return null;
            }
        }

    }

    /**
     * 使用使用gitee来登录
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        // 登录和注册合并逻辑
        // 向Gitee发送请求，得到该用户的信息
        Map<String,String> map = new HashMap<>();
        map.put("access_token",socialUser.getAccess_token());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map);

        if (response.getStatusLine().getStatusCode() == 200){
            //查询成功
            // 从响应体中获取用户信息
            String json = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(json);
            String id = jsonObject.getString("id");
            String name = jsonObject.getString("name");
            String login = jsonObject.getString("login");

            // 根据查到的用户id去数据库中查询，是否存在相同的用户
            MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", id));
            if (memberEntity != null){
                // 该用户已经存在了
                //更新用户的访问令牌的时间和access_token,并保存到数据库中
                MemberEntity update = new MemberEntity();
                update.setId(memberEntity.getId());
                update.setAccessToken(socialUser.getAccess_token());
                update.setExpiresIn(socialUser.getExpires_in());
                this.baseMapper.updateById(update);

                // 将查到的用户信息也一并更新
                memberEntity.setAccessToken(socialUser.getAccess_token());
                memberEntity.setExpiresIn(socialUser.getExpires_in());

                return memberEntity;
            }else {
                // 没有查到当前社交用户对应的记录我们就需要注册一个
                MemberEntity register = new MemberEntity();
                register.setExpiresIn(socialUser.getExpires_in());
                register.setAccessToken(socialUser.getAccess_token());
                register.setUsername(name);
                register.setNickname(login);
                register.setLevelId(1L);
                register.setCreateTime(new Date());
                register.setSocialUid(id);

                //把用户信息插入到数据库中
                this.baseMapper.insert(register);

                return register;

            }

        }else {
            // 查询用户信息失败
            throw  new GetGiteeInfoException();
        }
    }

}